
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
	<title>IOS Hybrid开发 - 与OC交互 - 乐の博客</title>
	<meta name="author" content="zhidong">

	
	<meta name="description" content="IOS Hybrid开发 - 与OC交互 原理： OC调用javascript是通过 1
[webView stringByEvaluatingJavaScriptFromString:@"document.title"]; javascript调用OC一般是通过在页面中发起一个特定的url请求 &hellip;">
	<meta name="keywords" content="iOS,Hybrid,Web">

  <!-- http://t.co/dKP3o1e -->
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

	<link href="/atom.xml" rel="alternate" title="乐の博客" type="application/atom+xml">
	
	<link rel="canonical" href="https://zhidong.rochu.cn/blog/2015/07/23/ios-hybridkai-fa-yu-ocjiao-hu/">
	<link href="/favicon.png" rel="shortcut icon">
	<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
	<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
	<script src="/javascripts/libs/jquery.min.js"></script>
	<!-- <link href='//fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'> -->
	
</head>


<body>
	<div class="container">
		<div class="left-col">
			<div class="intrude-less">
			<header id="header" class="inner"><div class="profilepic">	
	<script src="/javascripts/md5.js"></script>
	<script type="text/javascript">
		document.write("<img src='/images/pingtouge.png' alt='Profile Picture' style='width: 160px;' />");
	</script>
</div>
<h1><a href="/">乐の博客</a></h1>
<p class="subtitle">行而不思则罔，思而不行则怠</p>
<nav id="main-nav"><ul>
	<li><a href="/">Blog</a></li>
	<li><a href="/about">About</a></li>
	<li><a href="/portfolio">Portfolio</a></li>
	<li><a href="/archives">Archive</a></li>
</ul>
</nav>
<nav id="sub-nav">
	<div class="social">
		
		<a class="weibo" href="http://www.weibo.com/agdsdl" title="Weibo">Weibo</a>
		
		
		
		
		
		<a class="github" href="https://github.com/agdsdl" title="GitHub">GitHub</a>
		
		
		
		
		
		
		
		<a class="rss" href="/atom.xml" title="RSS">RSS</a>
		
	</div>
</nav>
<p class="description">知冬的后花园</p>
</header>				
			</div>
		</div>	
		<div class="mid-col">
			
				
			
			<div class="mid-col-container">
				<div id="content" class="inner"><article class="post" itemscope itemtype="http://schema.org/BlogPosting">
	<h1 class="title" itemprop="name">IOS Hybrid开发 - 与OC交互</h1>
	<div class="entry-content" itemprop="articleBody"><ul>
<li>原理：</li>
</ul>


<p>OC调用javascript是通过</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>[webView stringByEvaluatingJavaScriptFromString:@"document.title"];</span></code></pre></td></tr></table></div></figure>


<p>javascript调用OC一般是通过在页面中发起一个特定的url请求，然后在OC中响应</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType</span></code></pre></td></tr></table></div></figure>


<p>在响应中判断此url，并做相应的动作。</p>

<p>开源库：<a href="https://github.com/marcuswestin/WebViewJavascriptBridge">https://github.com/marcuswestin/WebViewJavascriptBridge</a></p>

<!-- more -->


<ul>
<li>WebView体验优化</li>
</ul>


<p>若页面结构多于一级，如这个导航顺序pageA->pageB->pageC，这时支持页面的返回就很必要。
也就是从pageC可以返回到pageB，pageB可以返回到pageA。</p>

<p>一般我们通过pushViewController来打开webViewController，而webViewController中加载pageA。
导航到pageB，pageC都是在webViewController中进行。</p>

<p>在pageC中点击导航栏的返回按钮的话，默认会退回到webViewController的上一级页面，而不是从pageC返回到pageB。
这就需要对导航栏的返回按钮做处理。为了优化体验，还需要到滑动手势做特殊处理。</p>

<p>开源库：<a href="https://github.com/agdsdl/DLPanableWebView">https://github.com/agdsdl/DLPanableWebView</a></p>

<ul>
<li>参数传递</li>
</ul>


<p>如上例，我们打开pageA时可以通过<code>[webView stringByEvaluatingJavaScriptFromString:@"document.title"];</code>来传参数给pageA
如果从pageA导航到pageB，要传递一个id到pageB，这时参数要怎么传递？
<code>stringByEvaluatingJavaScriptFromString</code>会将参数传给所有web页，用这个函数会导致我们的代码无比混乱。
目前业界常用的方式是通过sessionStorage, localStorage。localStorage是本地存储，长期有效。sessionStorage是会话期间的存储，一旦关闭webView，存储就会消失。
我们在项目中使用的时sessionStorage.</p>

<ul>
<li>插件化</li>
</ul>


<p>为了节省加载时间，提升用户体验，我们可以web功能模块打包成zip文件，一次性下载到本地。
使用时直接从本地加载，可以大大减少加载时间，同时也能节省不少带宽。</p>

<ul>
<li>调试</li>
</ul>


<p>纯web页面用chrome调试最方便。</p>

<p>hybrid开发中的webView用safari调试即可。
 * 在safari选项中勾选“显示开发菜单”。
 * 在手机或模拟器打开web页面的时候，在开发菜单中选择调试的页面。</p>

<ul>
<li>一些坑</li>
<li>stringByEvaluatingJavaScriptFromString要放在主线程调用。</li>
<li>从OC回调到js时，不能立即弹出alert，哪怕延时0秒弹出都行。</li>
</ul>

</div>

</article>
<!-- 
	<div class="share">
	<div class="addthis_toolbox addthis_default_style addthis_16x16_style">
	
	
	
	
	
	<a class="addthis_button_compact"></a>
	<a class="addthis_counter addthis_bubble_style"></a>
	</div>
  <script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid="></script>
</div>

 -->


<section id="comment">
    <h1 class="title">Comments</h1>
    <div id="gitalk-container"></div>
    <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
    <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
    <script>
    const gitalk = new Gitalk({
    clientID: '29bbf743e30b99394771',
    clientSecret: '41e4b7f1aa79742fc459f2971ad51596df5e4dda',
    repo: 'agdsdl.github.io',
    owner: 'agdsdl',
    admin: ['agdsdl'],
    id: location.pathname,      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
    })

    gitalk.render('gitalk-container')
    </script>
</section></div>
			</div>
			<footer id="footer" class="inner">Copyright &copy; 2019

    zhidong

<br>
Powered by Octopress.

Design credit: <a href="http://shashankmehta.in/archive/2012/greyshade.html">Shashank Mehta</a></footer>
			<script src="/javascripts/slash.js"></script>
<!-- <script src="/javascripts/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
	$('.fancybox').fancybox();
})(jQuery);
</script> Delete or comment this line to disable Fancybox -->




	<script type="text/javascript">
		var _gaq = _gaq || [];
		_gaq.push(['_setAccount', 'UA-65560025-1']);
		_gaq.push(['_trackPageview']);

		(function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		})();
	</script>



		</div>
	</div>
</body>
</html>
